<template>
  <div>
    <el-card>
      <div slot="header">发布文章</div>

      <el-form :model="formData" ref="Form" label-width="90px" :rules="addArticleRules">
        <el-form-item prop="title" label="文章标题:">
          <el-input v-model.trim="formData.title"></el-input>
        </el-form-item>
        <el-form-item prop="cate_id" label="文章分类:">
          <el-select style="width: 100%" v-model.trim="value">
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.name"
              :value="item.cate_name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="content" label="文章内容:">
          <quill-editor
            v-model.trim="formData.content"
            :options="{ placeholder: '这里可以填写内容' }"
            ref="myQuillEditor"
          >
          </quill-editor>
        </el-form-item>
        <el-form-item prop="cover_img" label="文章封面:  ">
          <div class="picBox" v-if="imgURL">
            <img :src="imgURL" alt="" />
          </div>
          <div class="imgBox" @click="openSelectFile" v-else>请选择封面</div>

          <div class="fileBox">
            <input
              type="file"
              id="fileBox-inp"
              ref="fileBox-inp"
              accept="image/*"
            />
            <div id="fileBox-text" @click="openSelectFile" ref="fileBox-text">
              <i class="el-icon-upload2"></i>
              选择封面
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="sendArticle(true)"
            >发布</el-button
          >
          <el-button size="mini" @click="sendArticle(false)"
            >存为草稿</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { getArtCate, publishArticle } from '@/api/article'
import { addArticleRules } from '@/utils/calidate-Rules'
import { addArtParams } from '@/utils/assets-data'

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      formData: {
        title: '',
        cate_id: '',
        content: '',
        state: '',
        cover_img: ''
      },
      cateList: [],
      value: '',
      imgURL: '',
      KEY: 'article',
      addArticleRules
    }
  },

  async created () {
    const { data } = await getArtCate()
    this.cateList = data

    // 读取本地数据映射到页面
    const localFormData = JSON.parse(localStorage.getItem(this.KEY)) || null
    if (localFormData) {
      this.imgURL = localFormData.cover_img
      if (localFormData.cover_img) {
        localFormData.cover_img = this.dataURLtoFile(localFormData.cover_img)
      }
      this.formData = localFormData
      this.value = this.cateList.find(
        (item) => item.id === localFormData.cate_id
      ).cate_name
    }
  },

  methods: {
    /**
     * @description:读取选择的文件转换为base64后存储 cover_img
     * @return {*}
     */
    openSelectFile () {
      const inputFile = this.$refs['fileBox-inp']
      const input = document.querySelector('#fileBox-inp')
      inputFile.click()
      input.addEventListener('change', () => {
        const File = input.files[0]
        //! 直接将文件作为参数传递 不用转base64 转base64位会转化位字符串
        this.formData.cover_img = File
        const reader = new FileReader()
        reader.readAsDataURL(File)
        reader.onload = () => {
          console.log(reader.result)
          // 将base64作为src的属性传递给 imgURL
          this.imgURL = reader.result
        }
      })
    },

    /**
     * @param {*} state:  发布 || 存为草稿
     * @return {*}
     */
    sendArticle (state) {
      this.formData.state = state ? '已发布' : '草稿'

      const params = new FormData()
      Object.keys(this.formData).forEach((key) => {
        params.append(key, this.formData[key])
      })

      if (state) {
        this.$refs.Form.validate((vailResult, obj) => {
          console.log(obj)
          if (vailResult) {
            publishArticle(params).then((res) => {
              this.$message.success(res.message)
              this.formData = {
                title: '',
                cate_id: '',
                content: '',
                state: '',
                cover_img: ''
              }
              this.imgURL = this.value = ''
              this.$refs.Form.resetFields()
              localStorage.removeItem(this.KEY)
            })
          }

          let arr = []
          for (const key in addArtParams) {
            Object.keys(obj).includes(key) && arr.push(addArtParams[key])
          }
          arr = arr.join('、')
          this.$message.error(`请填写${arr}`)
        })
      } else {
        this.formData.cover_img = this.imgURL
        localStorage.setItem(this.KEY, JSON.stringify(this.formData))
        this.$message.success('已存为草稿')
      }
    },

    /**
     * @description:将base64转为图片
     * @param {*} dataurl:base64
     * @param {*} filename:文件名
     * @return {*}
     */
    dataURLtoFile (dataurl, filename = 'file') {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    }
  },

  watch: {
    value (newValue) {
      const selectValue = this.cateList.find(
        (item) => item.cate_name === newValue
      )
      this.formData.cate_id = selectValue.id
    }
  }
}
</script>

<style scoped lang="less">
.el-card {
  :deep(.el-card__header) {
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 700;
    color: #131523;
    line-height: 22px;
  }
  .el-form {
    .el-form-item {
      // 图片盒子
      .imgBox {
        width: 496px;
        height: 252px;
        background: #f5f6fa;
        border-radius: 0px 0px 2px 2px;
        text-align: center;
        line-height: 252px;
        color: rgba(0, 0, 0, 0.4);
        cursor: pointer;
      }
      .fileBox {
        #fileBox-inp {
          display: none;
        }
        #fileBox-text {
          color: #4f81ff;
          cursor: pointer;
          .el-icon-upload2 {
            border: 1px dashed rgba(0, 0, 0, 0.4);
          }
        }
      }

      :deep(.el-form-item__label) {
        font-size: 14px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.9);
        line-height: 40px;
      }

      // 编辑器
      :deep(.el-form-item__content) {
        line-height: 24px;
        .quill-editor {
          .ql-container.ql-snow {
            height: 180px;
          }
        }
      }
    }
  }
}
</style>
